/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.plan.dao;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.javaeye.common.dto.DTO;
import com.javaeye.plan.dto.MaterialRequisiteForm;
import com.javaeye.plan.dto.MaterialRequisiteFormDetail;
import com.javaeye.plan.web.VoucherCondition;
import com.javaeye.common.web.PageInfo;

public class MaterialRequisiteFormDAOHibernate extends HibernateDaoSupport implements MaterialRequisiteFormDAO {
	
	@SuppressWarnings("unchecked")
	public int getMaxMaterialRequisiteFormId(String formId) {
		final String queryString = "select max(f.id) from MaterialRequisiteForm f where f.id like ?";
		List result = getHibernateTemplate().find(queryString, formId + "%");
		if (result.get(0) == null) {
			return 0;
		}
		String maxId = result.get(0).toString();
		maxId = maxId.replace(formId, "");
		return Integer.parseInt(maxId);
	}
	
	@Override
	public void saveMaterialRequisiteForm(final MaterialRequisiteForm form) {
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				List<Integer> removeDetailIds = form.getRemoveDetailIdList();
				for (int id : removeDetailIds) {
					MaterialRequisiteFormDetail detail = 
						(MaterialRequisiteFormDetail)session.load(MaterialRequisiteFormDetail.class, id);
					session.delete(detail);
				}
				session.saveOrUpdate(form);
				return null;
			}
		};
		getHibernateTemplate().execute(action);
	}
	
	public MaterialRequisiteForm getMaterialRequisiteForm(String formId) {
		MaterialRequisiteForm form = (MaterialRequisiteForm)getHibernateTemplate().get(MaterialRequisiteForm.class, formId);
		//由于使用延迟加载，这里需要强制取出关联集合
		Hibernate.initialize(form.getFormDetails());
		return form;
	}
	
	public void removeMaterialRequisiteForm(String formId) {
		MaterialRequisiteForm f = (MaterialRequisiteForm)getHibernateTemplate().load(MaterialRequisiteForm.class, formId);
		getHibernateTemplate().delete(f);
	}
	
	@SuppressWarnings("unchecked")
	public List getPageData(final DTO contidions, final PageInfo pageInfo) {
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				int pageIndex = pageInfo.getPageIndex();
				int pageSize = pageInfo.getPageSize();
				VoucherCondition contidion = (VoucherCondition)contidions;
				Criteria crit = session.createCriteria(MaterialRequisiteForm.class);
				
				Date beginDate = contidion.getBeginDate();
				Date endDate = contidion.getEndDate();
				if (beginDate != null && endDate != null) {
					crit.add(Restrictions.between("createDate", beginDate, endDate));
				}
				
				int type = contidion.getType();
				if (-1 != type) {
					crit.add(Restrictions.eq("type", type));
				}
				
				Integer[] typeList = contidion.getTypeList();
				if (typeList != null && typeList.length > 0) {
					crit.add(Restrictions.in("type", typeList));
				}
				
				int status = contidion.getStatus();
				if (-1 != status) {
					crit.add(Restrictions.eq("status", status));
				}
				
				Integer[] statusList = contidion.getStatusList();
				if (statusList != null && statusList.length > 0) {
					crit.add(Restrictions.in("status", statusList));
				}
				
				String voucherNo = contidion.getVoucherNo().trim();
				if (!"".equals(voucherNo)) {
					crit.add(Restrictions.like("id", "%" + voucherNo + "%"));
				}
				
				String batchNo = contidion.getBatchNo().trim();
				if (!"".equals(batchNo)) {
					crit.add(Restrictions.like("planNo", "%" + batchNo + "%"));
				}
				
				int skuId = contidion.getSkuId();
				if (skuId != -1) {
					crit.createAlias("formDetails", "d")
					.add(Restrictions.eq("d.materialId", skuId));
				}
				
				//按照创建日期倒序排序
				crit.addOrder(Order.desc("createDate"));
				
				crit.setProjection(Projections.rowCount());
				Integer rowNumber = (Integer)crit.uniqueResult();
				pageInfo.setCount(rowNumber);
				
				crit.setProjection(null);//取得了总数后,为了能够再次取得对象列表
				crit.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);//当hibernate采用关联的时候不使用这个返回的是个对象数组，加上这个返回的是当前列表的对象。
				crit.setFirstResult(pageIndex * pageSize);
				crit.setMaxResults(pageSize);
				return crit.list();
			}
		};
		return getHibernateTemplate().executeFind(action);
	}

}
